import time
import MySQLdb

from django.shortcuts import render_to_response
from django.http import HttpResponse

import pyxn.djangoxn as xn
from django.utils import simplejson

app_url = 'http://myapp.openapilabs.cn/apps/yktest/songli/'
app_app_url = 'http://apps.guanxi.koubei.com/py_songli/'
db_prefix = 'yk_'

flowers = ('','牡丹','玫瑰','菊花','月季','荷花','梅花','杜鹃','雪花','窗花','麻花');

@xn.require_add()
def foo(request):
    xn = request.xiaonei
    #make api calls now

    logging.debug('Testing users.getInfo')
    info = xn.users.getInfo(uids=[xn.uid,],
                    fields=["name","sex","hometown_location"])
    logging.debug('Got user info: %s' % info)

    logging.debug('Testing profile.getXNML')
    info = xn.profile.getXNML()
    logging.debug('Got user XNML: %s' % info)

    logging.debug('Testing profile.setXNML')
    info = xn.profile.setXNML(profile='<yk:name uid="profileowner"/>')
    logging.debug('setXNML result: %s' % info)

    logging.debug('Testing friends.get')
    info = xn.friends.get()
    logging.debug('Got friends: %s' % info)

    logging.debug('Testing friends.getFriends')
    info = xn.friends.getFriends()
    logging.debug('Got friends info: %s' % info)
    
    logging.debug('Testing friends.areFriends')
    info = xn.friends.areFriends(uids1=[xn.uid,], uids2=['12345678','87654321'])
    logging.debug('Got result: %s' % info)
    
    logging.debug('Testing friends.getAppUsers')
    info = xn.friends.getAppUsers()
    logging.debug('Got result: %s' % info)
    
    logging.debug('Testing friends.getAppFriends')
    info = xn.friends.getAppFriends()
    logging.debug('Got result: %s' % info)

    logging.debug('Testing feed.publishTemplatizedAction')
    info = xn.feed.publishTemplatizedAction(
           template_id='1',
           title_data=simplejson.dumps({'foo':'bar'}),
           body_data=simplejson.dumps({'bar':'baz'}),
           )
    logging.debug('Got result: %s' % info)

    logging.debug('Testing notifications.send')
    info = xn.notifications.send(to_ids=[xn.uid,'12345678'],
                                 notificatino=u'你好',
                                 )
    logging.debug('Got result: %s' % info)

    logging.debug('Testing invitations.getOsInfo')
    info = xn.invitations.getOsInfo(invite_ids=['id1','id2'])
    logging.debug('Got info: %s' % info)

    logging.debug('Testing invitations.getUserOsInviteCnt')
    info = xn.invitations.getUserOsInviteCnt(uids=['12345678','87654321'])
    logging.debug('Got info: %s' % info)

    logging.debug('Testing admin.getAllocation')
    info = xn.admin.getAllocation()
    logging.debug('Got allocation info: %s' % info)

    logging.debug('Testing pay.regOrder')
    info = xn.pay.regOrder(order_id=1234, amount=10)
    logging.debug('Got order result: %s' % info)

    logging.debug('Testing pay.isCompleted')
    info = xn.pay.isCompleted(order_id=1234)
    logging.debug('Payment is completed? %s' % info)

    logging.debug('Testing pay4Test.regOrder')
    info = xn.pay.regOrder(order_id=1234, amount=10)
    logging.debug('Got order result: %s' % info)

    logging.debug('Testing pay4Test.isCompleted')
    info = xn.pay.isCompleted(order_id=1234)
    logging.debug('Payment is completed? %s' % info)

    return HttpResponse('Hello!') 

def index(request):
    start = time.time()
    xn = request.xiaonei
    ok = ' '
    info = xn.check_session(request)
    uid = xn.uid
    if (request.POST.has_key('flower_id') and request.POST.has_key('friend_id')):
        fromuid = uid;
        touid = request.POST.get('friend_id')
        flower = request.POST.get('flower_id')
        message = request.POST.get('flower_message')
        db = MySQLdb.connect(user='root', db='apps', passwd='', host='localhost', charset='utf8')
        cursor = db.cursor()
        if cursor.execute("INSERT INTO yk_flowers (`from`, `to`, `time`, `flower`, `message`) VALUES ( '"+fromuid+"', '"+touid+"', "+str(int(start))+", "+flower+", '"+message+"')") == 1:
            ok = "您的礼物已送出。"
            body_data = '{"liwu":"' + str(flowers[int(flower)]) + '", "touser":"<yk:name uid=\''+str(touid)+'\' linked=\'true\' />", "game":"<a href=\'http://apps.guanxi.koubei.com/py_songli/\'>礼尚往来Python版</a>"}'
            xn.feed.publishTemplatizedAction(2,None,body_data,None)
            notification_info = '<yk:name uid="'+str(fromuid)+'" linked="true" /> 通过 <a href="http://apps.guanxi.koubei.com/py_songli/">礼尚往来Python版</a> 给你送了 ' + str(flowers[int(flower)]) + '！';
            xn.notifications.send(touid,notification_info)
        else:
            ok = "请再试一次。"

    friendslist = xn.friends.get()
    dataflowers = []
    i = 0
    for ainfo in flowers :
        if ainfo is not '':
            i += 1
            adata = { 'key': i, 'name': ainfo }
            dataflowers.append(adata)

    end = time.time()
    return render_to_response('index.html', {'app_url': app_url, 'app_app_url': app_app_url, 'runtime': (end-start)*1000,'index': True, 'dataflowers': dataflowers, 'friendslist': friendslist, 'havefriend': (len(friendslist)>0), 'info': ok})

def send(request):
    start = time.time()
    xn = request.xiaonei
    info = xn.check_session(request)
    uid = xn.uid
    db = MySQLdb.connect(user='root', db='apps', passwd='', host='localhost', charset='utf8')
    cursor = db.cursor()
    cursor.execute('SELECT * FROM `'+db_prefix+'flowers` WHERE `from` = \''+uid+'\' ORDER BY `time` DESC LIMIT 0 , 30')
    info = cursor.fetchall()
    data = []
    for ainfo in info :
        adata = { 'id': ainfo[0], 'from': ainfo[1], 'to': ainfo[2], 'time': ainfo[3], 'flower': ainfo[4], 'flowername': flowers[ainfo[4]], 'message': ainfo[5] }
        data.append(adata)

    db.close()
    end = time.time()
    return render_to_response('send.html', {'app_url': app_url, 'app_app_url': app_app_url, 'runtime': (end-start)*1000, 'send': True, 'data': data})

def receive(request):
    start = time.time()
    xn = request.xiaonei
    info = xn.check_session(request)
    uid = xn.uid
    db = MySQLdb.connect(user='root', db='apps', passwd='', host='localhost', charset='utf8')
    cursor = db.cursor()
    cursor.execute('SELECT * FROM `'+db_prefix+'flowers` WHERE `to` = \''+uid+'\' ORDER BY `time` DESC LIMIT 0 , 30')
    info = cursor.fetchall()
    data = []
    for ainfo in info :
        adata = { 'id': ainfo[0], 'from': ainfo[1], 'to': ainfo[2], 'time': ainfo[3], 'flower': ainfo[4], 'flowername': flowers[ainfo[4]], 'message': ainfo[5] }
        data.append(adata)

    db.close()
    end = time.time()
    return render_to_response('receive.html', {'app_url': app_url, 'app_app_url': app_app_url, 'runtime': (end-start)*1000, 'receive': True, 'data': data})

def invite(request):
    start = time.time()
    xn = request.xiaonei
    info = xn.check_session(request)
    uid = xn.uid
    info = xn.invitations.getUserOsInviteCnt(uids=[uid,])
    user_total = info[0]['user_total']
    end = time.time()
    return render_to_response('invite.html', {'app_app_url': app_app_url, 'runtime': (end-start)*1000, 'invite': True, 'user_total': user_total})

def mine(request):
    start = time.time()
    xn = request.xiaonei
    info = xn.check_session(request)
    uid = xn.uid
    info = xn.users.getInfo(uids=[uid,], fields=["name",])
    info = info[0]["name"]
    #info = xn.friends.get()
    db = MySQLdb.connect(user='root', db='apps', passwd='', host='localhost', charset='utf8')
    cursor = db.cursor()
    cursor.execute('SELECT * FROM `'+db_prefix+'users` WHERE `uid` = \''+uid+'\'')
    userinfo = cursor.fetchone()
    db.close()
    end = time.time()
    return render_to_response('mine.html', {'app_app_url': app_app_url, 'runtime': (end-start)*1000, 'mine': True, 'money': userinfo[3]})
